package work.flow.demo.api;


import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ProcessTest01 {

    @Qualifier("ProcessConfig")
    private final ProcessEngine processEngine;


    public ProcessTest01(ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    //发起流程
    @GetMapping("/p001")
    public String get01(@RequestParam Map<String, String> params) {
        //参数-发起人
        String name = params.get("name");

        //获取流程实例
        RuntimeService runtimeService = processEngine.getRuntimeService();
        // 设置流程发起人(与BPMN中的flowable:initiator对应)
        Map<String, Object> variables = new HashMap<>();
        variables.put("initiator", name);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("test_003", variables);

        return "Started process instance: " + processInstance.getId();
    }

    //流程流转1
    @GetMapping("/p002")
    public String get02(@RequestParam Map<String, String> params) {
        // 6. 查询并完成任务
        TaskService taskService = processEngine.getTaskService();

        // 6.1 处理部门1的任务 (lisi)
        List<Task> tasks = taskService.createTaskQuery()
                .taskAssignee("lisi")
                .processInstanceId("30025")//任务id
                .list();

        //处理任务
        for (Task task : tasks) {
            System.out.println("Processing task: " + task.getName() + " (id: " + task.getId() + ")");
            taskService.complete(task.getId());
            System.out.println("Completed task: " + task.getName());
        }

        return "流程流转1->当前共有 " + tasks.size() + "个处理任务";
    }

    //流程流转2
    @GetMapping("/p003")
    public String get03(@RequestParam Map<String, String> params) {
        // 6. 查询并完成任务
        TaskService taskService = processEngine.getTaskService();

        // 6.1 处理部门1的任务 (lisi)
        List<Task> tasks = taskService.createTaskQuery()
                .taskAssignee("wangwu")
                .processInstanceId("30025")//任务id
                .list();

        return "流程流转2->当前共有 " + tasks.size() + "个处理任务";
    }
}
